package com.hsd.whb.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsd.whb.code.ValidateCodeException;
import com.hsd.whb.enums.ResultEnum;
import com.hsd.whb.properties.SecurityConstants;
import com.hsd.whb.utils.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;


@Component
public class HwbAuthenctiationFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        if (exception instanceof ValidateCodeException) {
            response.getWriter().write(objectMapper.writeValueAsString(ResultVOUtil.error(500, exception.getMessage())));
        } else {
            response.getWriter().write(objectMapper.writeValueAsString(ResultVOUtil.error(ResultEnum.USERNAME_PASSWORD_ERROR)));
        }
    }

}
